'use strict'

const Service = require('egg').Service

// 微信网关token

class WxAppTokenService extends Service {
  constructor(props) {
    super(props)
    const { WxAppToken } = this.app.model
    this.state = {
      model: WxAppToken,
      args: {},
    }
    props.app.CommonService(this)
  }

  async findOrCreate(params) {
    const { WxAppToken } = this.app.model
    return WxAppToken.findOrCreate({
      where: params,
    })
  }

  /**
   * 获取微信 api token
   */
  getApiToken(appId, appSecret) {
    const { wechatApi } = this.app.lib

    return wechatApi.getToken(appId, appSecret)
  }

  /**
   * 直接拉取token
   */
  async getToken(appName) {
    const tokenObj = await this.findOne({ app_name: appName })

    return tokenObj && tokenObj.access_token ? tokenObj.access_token : null
  }
}

module.exports = WxAppTokenService
